package com.yun2s.tools.db;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;

/**
 * DerBy 数据库操作类 
 * @author "fanhm"
 *
 */
public class DerByDBConfig {

	public static final String derByDriver = "org.apache.derby.jdbc.ClientDriver";
	public static final String derByJDBC = "jdbc:derby://";
	
	public static boolean startDBMS(){
		return true;
	}
	
	/**
	 * 连接数据库
	 * @param dbSid
	 * @return
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws ClassNotFoundException
	 * @throws SQLException
	 */
	public static Connection getConn(String uri,String port, String dbSid){
        try {
			Class.forName(derByDriver).newInstance();
			return  DriverManager.getConnection(derByJDBC + uri + ":" + port + "/" + dbSid);
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
		return null;
	}
	
	public static  boolean createTable(Connection conn, TableClnDTO dto) throws SQLException{
		Statement st = conn.createStatement(); 
		return st.execute(dto.initCreateTableSQL());
	}
	
	public static boolean insertTable(Connection conn,ArrayList<TableClnDTO> tableClnDTOList) throws SQLException{
		boolean isSucc = true;
		Statement st = conn.createStatement();
		for(TableClnDTO dto:tableClnDTOList){
			dto.setExeResult(st.execute(dto.initInsertSQl()));
			isSucc = isSucc&&dto.isExeResult();
		}
		return isSucc;
		
	}
	
	/**
	 * TEST
	 * @param args
	 */
	public static void main(String[] args){
		 /**
		  * Test Connection 
		  */
		Connection conn = DerByDBConfig.getConn("localhost", "1527", "datacheck");
		TableClnDTO dto = new TableClnDTO("pol_info");
		ArrayList<TableClnDTO> tableClnDTOList = new ArrayList<TableClnDTO>();
		try {
//			DerByDBConfig.createTable(conn, dto);
			
			dto.setPolno("sfsfdf");
			dto.setAmount(new BigDecimal(3545.34));
			dto.setCreateDate(new Date());
			tableClnDTOList.add(dto);
			DerByDBConfig.insertTable(conn, tableClnDTOList);
			
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
	}
	
	
}
